package com.clover.exception;

import com.clover.dto.ErrorInfoDto;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常捕获器
 * @author FoLafClover
 * @date 2018/5/7/007
 */
@ControllerAdvice
public class GlobalExceptionHandler extends DefaultHandlerExceptionResolver{

    @ExceptionHandler( value = Exception.class)
    public ModelAndView defaultErrorHandler(HttpServletRequest req , Exception e){
        ModelAndView mv = new ModelAndView();
        mv.addObject("exception", e);
        mv.addObject("url", req.getRequestURL());
        if( e instanceof org.springframework.web.servlet.NoHandlerFoundException) {
            mv.setViewName("404");
        }else {
            mv.setViewName("500");
        }
        return mv;
    }

    @ExceptionHandler( value = WebException.class)
    public ModelAndView webException( HttpServletRequest req, WebException we){
        ModelAndView mv = new ModelAndView();
        mv.addObject("exception", we);
        mv.addObject("url", req.getRequestURL());
        mv.setViewName("500");
        return mv;
    }

    @ExceptionHandler( value = AppException.class)
    @ResponseBody
    public ErrorInfoDto appException(HttpServletRequest req, AppException ae){
        ErrorInfoDto dto = new ErrorInfoDto();
        dto.setMsg(ae.getMessage());
        dto.setCode(500);
        dto.setUrl(req.getRequestURL().toString());
        return dto;
    }
}
